package com.aiju.common.manager;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: 佐为
 * @date: 2017-03-02 16:44
 * @version: V1.0
 * @Description: 享元工厂，缓存对象（享元模式和单例模式目的相同，减少内存的开销）
 */
class ServiceFactoryImpl implements ServiceFactory {

    private Map<String, Object> mapClass = new ConcurrentHashMap();

    @Override
    public <T> T getService(Class<T> serviceClass) {
        String className = serviceClass.getName();
        if (mapClass.containsKey(className)) {
            return (T) mapClass.get(className);
        } else {
            T service = null;
            try {
                service = serviceClass.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            mapClass.put(className, service);
            return service;
        }
    }

}
